#!/bin/bash

# 设置变量
REPO_URL="git@codeup.aliyun.com:6057eaece55ebe2b84685897/rczy/rczy-ocr/weigh-ocr.git"  # 替换为你的Git仓库URL
CLONE_DIR="/data/ocrapp/weigh-ocr"  # 替换为你想要克隆代码到的目录
DEPLOY_DIR="/data/ocrapp"
IMAGE_NAME="zy_ocr"  # 替换为你的Docker镜像名称
COMPOSE_FILE="docker-compose.yaml"  # Docker Compose文件路径
SERVICE_NAME="ocr_container"  # Docker Compose中定义的服务名称
LISTEN_PORT=80  # 要检查的监听端口

# 克隆Git仓库
echo "Cloning Git repository..."
if [ -d "$CLONE_DIR" ]; then
    echo "Directory $CLONE_DIR already exists, pulling latest changes..."
    cd "$CLONE_DIR" && git pull origin prod  # 假设你的默认分支是main
else
    echo "Cloning into $CLONE_DIR..."
    git clone "$REPO_URL" "$CLONE_DIR"
fi

# 获取当前日期和时间作为标签（格式化为YYYYMMDD_HHMMSS）
TAG=$(date +"%Y%m%d_%H%M%S")

# 构建Docker镜像
echo "Building Docker image with tag $TAG..."
cd "$CLONE_DIR" && docker build -t "$IMAGE_NAME:$TAG" .

# 更新docker-compose.yml中的镜像标签
[ -f $DEPLOY_DIR/$COMPOSE_FILE ] && rm $DEPLOY_DIR/$COMPOSE_FILE
cp -ar $CLONE_DIR/$COMPOSE_FILE  $DEPLOY_DIR
echo "Updating docker-compose.yaml with tag $TAG..."
sed -i "s/IMAGE_TAG/$TAG/" "$DEPLOY_DIR/$COMPOSE_FILE"

# 使用Docker Compose部署
echo "Deploying with Docker Compose using tag $TAG..."
cd "$DEPLOY_DIR" && docker compose -f "$COMPOSE_FILE" up -d 

# 等待服务启动（可能需要调整等待时间）
sleep 10

# 检查服务是否在监听端口80
echo "Checking if $SERVICE_NAME service is listening on port $LISTEN_PORT..."
if netstat -tuln | grep ":$LISTEN_PORT " > /dev/null; then
    echo "Deployment successful! $SERVICE_NAME service is listening on port $LISTEN_PORT"
else
    echo "Deployment failed! $SERVICE_NAME service is not listening on port $LISTEN_PORT"
    exit 1
fi

exit 0
